package com.accp.www.chat;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ChatRoom {

	private String name;
	private List<ChatUser> userList=new ArrayList<ChatUser>();
	private List<ChatMessage> messageList=new ArrayList<ChatMessage>();
	
	public ChatRoom(String name) {
		this.name=name;
	}

	public String getName() {
		return name;
	}

	void addUser(ChatUser user) {
		userList.add(user);
	}

	public List<ChatUser> getUsers() {
		return userList;
	}

	public List<ChatMessage> getMessages(ChatUser user) {
		List<ChatMessage> list=new LinkedList<ChatMessage>();
		for (int i = 0; i < this.messageList.size(); i++) {
			ChatMessage msg = messageList.get(i);
			if(msg.getSendTime().getTime()>=user.getInRoomTime().getTime()
				&& ( msg.getType()==ChatMessage.TYPE_SYSTEM || msg.getType()==ChatMessage.TYPE_PUBLIC || msg.getFromUser()==user || msg.getToUser()==user)){
				list.add(msg);
			}
		}
		return list;
	}

	public void addMessage(ChatMessage chatMessage) {
		this.messageList.add(chatMessage);
	}

	public ChatUser getUserByName(String userName) {
		for(int i=0;i<this.userList.size();i++){
			if(this.userList.get(i).getName().equals(userName)){
				return this.userList.get(i);
			}
		}
		return null;
	}

	public boolean removeUser(ChatUser user) {
		return this.userList.remove(user);
	}

	public boolean removeUser(String name) {
		Iterator<ChatUser> it=this.userList.iterator();
		while(it.hasNext()){
			ChatUser user=it.next();
			if(user.getName().equals(name)){
				this.userList.remove(user);
				return true;
			}
		}
		return false;
	}
}
